package org.jeecg.modules.miniAppCustomerEndPoint.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.miniAppCustomerEndPoint.constant.JxCustomerConstant;
import org.jeecg.modules.miniAppCustomerEndPoint.entity.JxOrderDo;
import org.jeecg.modules.miniAppCustomerEndPoint.entity.JxSiteMenuDo;
import org.jeecg.modules.miniAppCustomerEndPoint.enums.JxOrderStateEnum;
import org.jeecg.modules.miniAppCustomerEndPoint.mapper.JxOrderMapper;
import org.jeecg.modules.miniAppCustomerEndPoint.mapper.JxSiteMenuMapper;
import org.jeecg.modules.platformMasterEndPoint.utils.JxOrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class JxOrderScheduledTask {

    @Autowired
    private JxSiteMenuMapper jxSiteMenuMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JxOrderMapper jxOrderMapper;

    @Autowired
    private JxOrderServiceImpl jxOrderServiceImpl;

    @Autowired
    private JxWxPayServiceImpl wxPayServiceImpl;
    /**
     * 1. 每天中午13点，从jx_site_menu表中，读取各个菜品的默认库存值，将各个店铺的菜品库存，重置成为库存值
     * 2. 每天中午13点，从jx_order表中，状态为toPay 待支付的订单，全部调用接口，终止交易，并将订单状态设置为 canceled
     */
//    @Scheduled(cron = "10 * * * * *")
    @Scheduled(cron = "0 0 13 * * *")
    public void resetFoodStock() {

        List<JxSiteMenuDo> list = jxSiteMenuMapper.selectList(new LambdaQueryWrapper<JxSiteMenuDo>());
        for (int i = 0 ; i < list.size() ; i ++) {

            JxSiteMenuDo siteMenuDo = list.get(i);
            String siteId = siteMenuDo.getSiteId();
            String storeId = siteMenuDo.getStoreId();
            String storeFoodStockKey = "stock_" + siteId +"_" + storeId;

            String foodId = siteMenuDo.getFoodId();
            Integer stock = siteMenuDo.getLimitCount();
            redisUtil.hset(storeFoodStockKey, foodId, stock);
        }

        // 将 取餐编号重置为 1
        redisUtil.set(JxCustomerConstant.JX_ORDER_PICKUP_CODE, 0);
    }

    //    @Scheduled(cron = "10 * * * * *")
    @Scheduled(cron = "0 0 13 * * *")
    public void handleUnPayedOrders() {

        // 将所有状态为 待支付的订单，调用微信支付平台的 终止支付接口，取消支付交易
        List<JxOrderDo> toPayOrders = jxOrderMapper.selectList(new LambdaQueryWrapper<JxOrderDo>().eq(JxOrderDo::getState, JxOrderStateEnum.TOPAY.getValue()));
        log.info("找到 {} 个状态为 未支付的订单，调用微信支付平台 终止支付接口，终止支付交易", toPayOrders.size());
        for (int k = 0 ; k < toPayOrders.size(); k ++) {
            JxOrderDo jxOrderDo = toPayOrders.get(k);
            wxPayServiceImpl.closeTransaction(jxOrderDo.getId());

            JxOrderDo newStateOrder = new JxOrderDo();
            newStateOrder.setState(JxOrderStateEnum.CANCELED);
            newStateOrder.setId(jxOrderDo.getId());
            jxOrderMapper.updateById(newStateOrder);
        }
    }

    /**
     * 每天中午11:15点，将所有订单状态更新为 已发货，待收货; 正常情况下，应该是 站长通过 站长端小程序来设置各个店铺供应的订单的状态，
     * 此处是订单状态设置为 待收货的 最晚时间，避免站长忘记操作导致的订单状态一直为待发货
     */
//    @Scheduled(cron = "10 * * * * *")
    @Scheduled(cron = "0 15 11 * * *")
    public void setAllOrderToReceive() {

        log.info("将所有状态为【待配送】订单，状态变更为【待收货】");
        // 11:15 将所有 待配送（2） 更新为 待收货（3）
        String oldState = jxOrderServiceImpl.mapOrderTypeCode2String(2);
        String newState = jxOrderServiceImpl.mapOrderTypeCode2String(3);
        Integer dateFlag = JxOrderUtil.todayFlagForIndex();
        Integer updateCount = jxOrderMapper.updateAllOrderToState(dateFlag, oldState, newState);
        log.info("将所有状态为【待配送】订单，状态变更为【待收货】，更新成功个数：{}", updateCount);
    }

}
